const express = require('express');
const fs = require('fs');

//获取json数据
var data = require('./data.json');

exports.FindID = function(url,callback) {
  url.id = parseInt(url.id);
  var book = data.Books.find(item => item.id === url.id)
  callback(book)
}
exports.add = function(body,callback) {
   body.id = data.Books.length + 1;
   data.Books.push(body);
   console.log(body);

   // 转为字符串
   var Data = JSON.stringify({
     Books: data.Books,
   });

   GetWrite('./data.json',Data,callback)
}
exports.edit = function(body,callback){
  body.id = parseInt(body.id);
  var book = data.Books.find(item => item.id === body.id);

  // 遍历req.body对象
  for (var k in body) {
    book[k] = body[k];
  }

  var Data = JSON.stringify({
    Books: data.Books,
  });

  GetWrite('./data.json',Data,callback)
}
exports.delete = function(url,callback){
  url.id = parseInt(url.id);
  var index = data.Books.findIndex(item => item.id === url.id);

  data.Books.splice(index, 1);

  var Data = JSON.stringify({ Books: data.Books });
  GetWrite('./data.json',Data,callback)
}

// 定义一个写入 API()
function GetWrite(path,Data,callback){
  fs.writeFile(path, Data, err => {
    if (err) {
      callback(err);
    }
    callback(null);
  });
}